const api = require('../../utils/request.js');

Page({
  data: {
    entity: null,
    loading: true,
    errMsg: '',
    isCharacter: false
  },

  onLoad: function(options) {
    const id = options.id;
    const type = options.type; // 'character' 或 'person'
    console.log(id);
    this.setData({ isCharacter: type === 'character' });
    if (type === 'character') {
      this.loadCharacterDetail(id);
    } else if (type === 'person') {
      this.loadPersonDetail(id);
    }
  },

  // 预处理 infobox 数据，添加类型判断结果
  processInfobox(infobox) {
    return infobox.map(item => {
      const value = item.value;
      let type = '';
      if (typeof value === 'string') {
        type = 'string';
      } else if (Array.isArray(value)) {
        type = 'array';
      } else {
        type = 'other';
      }
      return {
        ...item,
        valueType: type
      };
    });
  },

  loadCharacterDetail: function(characterId) {
    api.getCharacterById(characterId)
      .then((res) => {
        const processedInfobox = this.processInfobox(res.infobox);
        this.setData({
          entity: {
            ...res,
            infobox: processedInfobox
          },
          loading: false
        });
      })
      .catch((err) => {
        console.error('Error loading character detail:', err);
        this.setData({
          errMsg: '加载角色详情失败',
          loading: false
        });
      });
  },

  loadPersonDetail: function(personId) {
    api.getPersonById(personId)
      .then((res) => {
        this.setData({
          entity: res,
          loading: false
        });
      })
      .catch((err) => {
        console.error('Error loading person detail:', err);
        this.setData({
          errMsg: '加载人物详情失败',
          loading: false
        });
      });
  }
});